import subprocess
from appium.webdriver import Remote
from appium.options.android import UiAutomator2Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


def check_adb_devices():
    """检查连接的ADB设备"""
    result = subprocess.getoutput("adb devices")
    devices = [line.split("\t")[0] for line in result.split("\n")[1:] if "device" in line]
    if not devices:
        raise ConnectionError("未检测到任何Android设备/模拟器\nADB输出:\n" + result)
    print(f"检测到设备: {devices}")
    return devices


def get_android_version():
    """获取设备Android版本"""
    return subprocess.getoutput("adb shell getprop ro.build.version.release").strip()


def start_appium_session():
    """启动Appium会话"""
    # 检查设备
    check_adb_devices()

    # 配置选项
    options = UiAutomator2Options()
    options.platform_name = 'Android'
    options.platform_version = get_android_version()  # 自动获取版本
    options.device_name = '1b0262d3'  # 修改为你的设备ID
    options.app_package = 'com.ybmmarket20.debug'  # 修改为你的应用包名
    options.app_activity = '.MainActivity'  # 修改为你的启动Activity
    options.no_reset = True
    options.automation_name = 'UiAutomator2'
    options.new_command_timeout = 300
    options.skip_device_initialization = True  # 添加这一行

    print("正在启动Appium会话...")
    driver = Remote('http://localhost:4723', options=options)
    # 其余代码保持不变...

if __name__ == '__main__':
    start_appium_session()